/*
  Main Program Loop
*/

#define SHORT_PERIOD 5000
#define LONG_PERIOD 10000
#define MAXMINILOG 500
#define COMMANDLENGTH 4

/* Defintion of on board command codes */
#define CMD_SDON 0x1
#define CMD_PAYON 0x2
#define CMD_RESET 0x3

#include <msp430x16x.h>
#include <signal.h>

#include "main.h"

#include "log/log.h"
#include "timing/timing.h"
#include "recovery/recover.h"
#include "i2c/i2c.h"
#include "sd/sd.h"
#include "payload/pay.h" /* removes implicit decleration warning on line 106 */


//Global variables for passing commands from interrupts to main function
int command, significance, commandToken;

/* Clears the command variables */
void reset_command() {
  command=0;
  significance=0;
  commandToken=0;
}

/* Builds up a command bit by bit until it is complete */
int command_stack(char bit) {
  int i;

  if (commandToken==1) return 0;

  command+=bit<<significance++;
  if (significance==COMMANDLENGTH) {
    significance=0;
    commandToken=1;
  }
  return 1;
}

/* Reacts to a rise on P2.0 and reads a bit from P2.1  for commands */
/*interrupt(PORT2_VECTOR) command_bit() {
  command_stack((P2IN & 0x2)/2);
  P5DIR=255;
  P5OUT=255-P5OUT;
  P2IE=1;
  P2IFG=0;
  }*/

/* Entry point */
int main() {
  unsigned long int address=0;
  unsigned char minilog[MAXMINILOG];
  int logIndex=0;

  /* 
     log mode variable

     0=minilog
     1=log

     char rather than boolean to allow for future modes

   */
  char logMode=0;

  //recover(); //Call recovery code

  //TBCTL=0x01D2; //Set Timer B to ACLK/8, count up, interrupt enable
  //TBCCTL0=0x0430; //Sets CC register 0 to compare and enables interrupt

  P1DIR=255;
  P1OUT=0;

  //reset_command();
  //P2DIR=0;
  //P2SEL=0;
  //P2IE=1;

  //Runs a test of the I2C component
  //i2ctest();

  //Temporary command to always enable SD card
  sdInit();
  logMode=1;

//Enter an infinite loop. Interrupts handle everything from this point
  while(1) {
    P1OUT=255-P1OUT;

    /* Act on any new commands passed */
    if (commandToken>0) {
      if (CMD_RESET) break;

      switch (command) {
      case CMD_SDON:
	if (sdInit()) logMode=1;
	break;

      case CMD_PAYON:
	payload_init(10, 'x');
	break;

      default:
	break;
      }
      reset_command();
    }

    /*log_entry(0); //temporary simplification to check logging*/

    /* Log data, based on whether or not SD is powered up */
    /*if (logMode==1) {
      waitms(SHORT_PERIOD);
      address+=(unsigned long int)log_entry(address);
      address+=16;
      P1OUT=(char)(address & 0xff);
    }
    else {
      waitms(LONG_PERIOD);
      logIndex+=minilog_entry(&minilog[logIndex]);
      P1OUT=(char)(logIndex & 0xff);
      if (logIndex>=MAXMINILOG) logIndex=0;
      }*/
  }

}
